// app/service/wechatPay.js
'use strict';
 
// cnpm install qr-image --save
const QrImage = require('qr-image');
 
const WechatPay = require('../library/wechatPay.js');
const Service = require('egg').Service;
 
class WechatPayService extends Service {
 
  // 执行支付
  async doPay(orderData) {
    return new Promise((resove,reject) => {
      let pay = new WechatPay(this.config.wechatPayConfig);
      let notify_url = this.config.wechatPayBasicParams.notify_url;
      let out_trade_no = orderData.out_trade_no;
      let title = orderData.title;
      let price = orderData.price * 100;
      let ip = this.ctx.request.ip.replace(/::ffff:/, '');
      pay.createOrder({
        openid: '',
        // 微信支付完成后的回调
        notify_url: notify_url, 
        // 订单号
        out_trade_no: out_trade_no, 
        attach: title,
        body: title,
        // 此处的额度为分
        total_fee: price.toString(), 
        spbill_create_ip: ip
      }, function (error, response) {
        if (error) {
          reject(error);
        };
        resove(response.code_url);
      });
    })
  }
 
  // 生成二维码
  async qrImage(url) {
    let image = QrImage.image(url, { type: 'png' });
    return image;
  }
 
  // 接收微信官方提交的数据
  wechatPayNotify(params) {
    let pay = new WechatPay(this.config.wechatPayConfig);
    let notifyObj = params;
    let signObj = {};
    for (let attr in notifyObj) {
      if (attr != 'sign') {
        signObj[attr] = notifyObj[attr]
      }
    }
    let sign = pay.getSign(signObj);
    return sign;
  }
 
}
 
module.exports = WechatPayService;